package com.wlz.list;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListTest {

    private static volatile CopyOnWriteArrayList<String> arrayList = new CopyOnWriteArrayList<>();

    public static void main(String[] args)throws InterruptedException{
        test2();
        //1、数据不一致
        //2、List数据量很大   会占用双倍内存
        //Collections.synchronizedList(new ArrayList<>());跟vector差不多
        //CopyOnWriteArrayList
    }

    public static void test2() throws InterruptedException{
        arrayList.add("a");
        arrayList.add("b");
        arrayList.add("c");
        arrayList.add("d");
        arrayList.add("e");

        Thread threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                arrayList.set(0, "z");
                arrayList.remove(2);
                arrayList.remove(3);
                System.out.println("线程"+arrayList);
            }
        });

        Iterator<String> itr = arrayList.iterator();

        threadOne.start();
        threadOne.join();//等待线程执行完毕

        while (itr.hasNext())
            System.out.println(itr.next());
    }

    public static void  test1(){
        for(int i = 0; i<100; i++){
            arrayList.add("string" + i);
        }
        for (int i = 0; i<100; i++) {
            System.out.println(arrayList.get(i));
            arrayList.remove(i);
        }
    }
    public static void test(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                test1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test1();
            }
        }).start();
    }


}
